import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:seedfour/app/models/dictionary_entity.dart';
import 'package:seedfour/app/models/org_name_entity.dart';
import 'package:seedfour/app/remote/request.dart';
import 'package:seedfour/app/routes/app_routes.dart';

import '../../../models/api_response/list_data_entity.dart';
import '../../../models/case_order_info_entity.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

enum CaseCreatePageType {
  create,
  query,
  seal,
}

class CaseCreateLogic extends GetxController {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  late CaseCreatePageType pageType;

  late GlobalKey<FormState> formKey;
  late TextEditingController remarkController;
  late TextEditingController caseNameController;
  late TextEditingController searchCaseNameController;
  late TextEditingController searchCaseCodeController;

  final caseClientTexts = <LegalPersonController>[].obs;
  final caseOppositeTexts = <LegalPersonController>[].obs;
  final caseThirdTexts = <LegalPersonController>[].obs;

  final caseType = Rxn<CaseType>();
  final lawsuitType = Rxn<LawsuitType>();
  final caseBusinessType = Rxn<DictionaryEntity>();
  final caseClassType = Rxn<DictionaryEntity>();

  final caseBusinessTypes = <DictionaryEntity>[].obs;
  final caseClassTypes = <DictionaryEntity>[].obs;

  final isCreating = false.obs;
  final hasOpposite = true.obs;
  final hasThird = true.obs;

  var orgNames = <String>[].obs;

  @override
  void onInit() {
    super.onInit();

    pageType = Get.arguments;

    formKey = GlobalKey<FormState>();
    remarkController = TextEditingController();
    caseNameController = TextEditingController();
    searchCaseNameController = TextEditingController();
    searchCaseCodeController = TextEditingController();

    caseClientTexts.add(LegalPersonController(
        TextEditingController(), TextEditingController()));
    caseOppositeTexts.add(LegalPersonController(
        TextEditingController(), TextEditingController()));
    caseThirdTexts.add(LegalPersonController(
        TextEditingController(), TextEditingController()));

    _getCaseBusinessTypes();
    _getCaseClassTypes();
  }

  void setNotCaseOpposite(bool value) {
    hasOpposite.value = value;
    if (value) {
      caseOppositeTexts.add(LegalPersonController(
          TextEditingController(), TextEditingController()));
    } else {
      caseOppositeTexts.clear();
    }
  }

  void setNotThirdList(bool value) {
    hasThird.value = value;
    if (value) {
      caseThirdTexts.add(LegalPersonController(
          TextEditingController(), TextEditingController()));
    } else {
      caseThirdTexts.clear();
    }
  }

  Future<List<String>> searchOrg(String name) async {
    if (name.isEmpty) {
      return [];
    }
    ListDataEntity<OrgNameEntity>? result = await apiService.searchOrg(name);
    if (result != null) {
      orgNames.clear();
      orgNames.addAll(result.data!.map((e) => e.name!).toList());
      return orgNames;
    }
    return [];
  }

  void createCase() {
    final clientName = caseClientTexts[0].nameController.text;
    final clientCode = caseClientTexts[0].codeController.text;

    final oppositeName = caseOppositeTexts.isNotEmpty
        ? caseOppositeTexts[0].nameController.text
        : '';
    final oppositeCode = caseOppositeTexts.isNotEmpty
        ? caseOppositeTexts[0].codeController.text
        : '';

    final thirdName =
        caseThirdTexts.isNotEmpty ? caseThirdTexts[0].nameController.text : '';
    final thirdCode =
        caseThirdTexts.isNotEmpty ? caseThirdTexts[0].codeController.text : '';

    final otherInfo = CaseOrderInfoEntity(
            caseClientList: caseClientTexts
                .sublist(1)
                .map((e) => LegalPerson(
                    name: e.nameController.text, code: e.codeController.text))
                .toList(),
            caseOppositeList: caseOppositeTexts.isNotEmpty
                ? caseOppositeTexts
                    .sublist(1)
                    .map((e) => LegalPerson(
                        name: e.nameController.text,
                        code: e.codeController.text))
                    .toList()
                : [],
            caseThirdList: caseThirdTexts.isNotEmpty
                ? caseThirdTexts
                    .sublist(1)
                    .map((e) => LegalPerson(
                        name: e.nameController.text,
                        code: e.codeController.text))
                    .toList()
                : [])
        .toString();

    final suitType = caseType.value == null ? '' : caseType.value!.value;
    final lawsuitType =
        this.lawsuitType.value == null ? '' : this.lawsuitType.value!.value;
    final caseBusinessValue =
        caseBusinessType.value == null ? '' : caseBusinessType.value!.value;
    final caseClassValue =
        caseClassType.value == null ? '' : caseClassType.value!.value;

    pageType == CaseCreatePageType.query
        ? _queryCase(
            searchCaseNameController.text,
            searchCaseCodeController.text,
            oppositeName: oppositeName,
            oppositeCode: oppositeCode,
            thirdName: thirdName,
            thirdCode: thirdCode,
            otherInfo: otherInfo,
            suitType: suitType,
            lawsuitType: lawsuitType,
            caseBusinessValue: caseBusinessValue,
            caseClassValue: caseClassValue,
            remarks: remarkController.text,
          )
        : _createCase(
            clientName,
            clientCode,
            oppositeName: oppositeName,
            oppositeCode: oppositeCode,
            thirdName: thirdName,
            thirdCode: thirdCode,
            otherInfo: otherInfo,
            suitType: suitType,
            lawsuitType: lawsuitType,
            caseBusinessValue: caseBusinessValue,
            caseClassValue: caseClassValue,
            remarks: remarkController.text,
            caseName: caseNameController.text,
          );
  }

  void _getCaseBusinessTypes() {
    caseBusinessTypes.clear();
    apiService.listDictionary('case_business').then((value) => {
          if (value != null) {caseBusinessTypes.addAll(value.data!)}
        });
  }

  void _getCaseClassTypes() {
    caseClassTypes.clear();
    apiService.listDictionary('case_class').then((value) => {
          if (value != null) {caseClassTypes.addAll(value.data!)}
        });
  }

  void getCompanyInfo(String name, TextEditingController codeController) {
    if (name.isEmpty) {
      return;
    }

    apiService.getCompanyInfo(name).then((value) {
      if (value != null) {
        codeController.text = value.value['data']['nsrsbh'];
      }
    });
  }

  void _queryCase(
    String clientName,
    String clientCode, {
    String? oppositeName,
    String? oppositeCode,
    String? thirdName,
    String? thirdCode,
    String? otherInfo,
    String? suitType,
    String? lawsuitType,
    String? caseBusinessValue,
    String? caseClassValue,
    String? remarks,
  }) =>
      request(() async {
        isCreating.value = true;
        var result = await apiService.caseQuery(clientName, clientCode,
            oppositeName: oppositeName,
            oppositeCode: oppositeCode,
            thirdName: thirdName,
            thirdCode: thirdCode,
            otherInfo: otherInfo,
            suitType: suitType,
            lawsuitType: lawsuitType,
            caseBusinessValue: caseBusinessValue,
            caseClassValue: caseClassValue,
            remarks: remarks);

        isCreating.value = false;

        if (result != null) {
          Get.snackbar('提示', '查询成功');
          Get.toNamed(RouteGet.caseQuery, arguments: result.conflict);
        }
      }, showLoading: true, message: '查询中...');

  void _createCase(
    String clientName,
    String clientCode, {
    String? oppositeName,
    String? oppositeCode,
    String? thirdName,
    String? thirdCode,
    String? otherInfo,
    String? suitType,
    String? lawsuitType,
    String? caseBusinessValue,
    String? caseClassValue,
    String? remarks,
    String? caseName,
  }) =>
      request(() async {
        isCreating.value = true;
        var result = await apiService.createCase(clientName, clientCode,
            oppositeName: oppositeName,
            oppositeCode: oppositeCode,
            thirdName: thirdName,
            thirdCode: thirdCode,
            otherInfo: otherInfo,
            suitType: suitType,
            lawsuitType: lawsuitType,
            caseBusinessValue: caseBusinessValue,
            caseClassValue: caseClassValue,
            remarks: remarks,
            caseName: caseName);

        isCreating.value = false;

        if (result != null) {
          pageType == CaseCreatePageType.seal
              ? Get.back(result: result)
              : Get.offNamed(RouteGet.caseDetail, arguments: result.id);
          Get.snackbar('提示', '创建成功');
        }
      }, showLoading: true, message: '创建中...');
}

enum CaseType {
  lawsuit('诉讼', 'lawsuit'),
  nonLawsuit('非诉讼', 'nosuit'),
  arbitration('法律援助', 'legalaid');

  const CaseType(this.label, this.value);

  final String label;
  final String value;
}

enum LawsuitType {
  criminal('刑事', 'criminal'),
  civil('民事', 'civil'),
  administration('行政', 'administration'),
  arbitration('仲裁', 'arbitration');

  const LawsuitType(this.label, this.value);

  final String label;
  final String value;
}

class LegalPersonController {
  final TextEditingController nameController;
  final TextEditingController codeController;

  LegalPersonController(this.nameController, this.codeController);
}
